import router from './router'
import store from './store'
import {loadroot2} from './utils/menuUtil'
import cryptodes from '@/utils/CryptoJsUtil'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getSid, getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Cookies from 'js-cookie'
import common from '@/utils/common'
import {syncRequest} from '@/utils/httpRequet'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
export const defaultRoot="";
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  const sid=getSid();
  if (hasToken) {
    //权限控制
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      let userinfo=store.state.user.userInfo;
      if(_.isEmpty(userinfo)){
        let res=syncRequest({url:'userinfo'});
        if(!res || res.error){
          store.dispatch("user/resetToken")
          store.dispatch('tagsView/delAllViews', null, { root: true })
          return;
        }
        store.dispatch("user/setUserInfo",res.user);
      }
      let subsysid=to.query.root||defaultRoot;
      if(to.query.pm){
        let pm=(cryptodes.decryptByDES(decodeURIComponent(to.query.pm)));
        store.dispatch("business/setValues",{root:'pageParam',values:JSON.parse(pm)});
      }
      if(typeof subsysid=="undefined" || subsysid==""){
        if(to.path=='/portal'){//
          next();
          return;
        }
        next({path:'/portal'})
        return;
      }else if(subsysid=='nomenu'){
        next();
        return;
      }else{
        common.subsysinfo.curid=subsysid;
        if(store.state.permission.isLoaded==false){
          let info=loadroot2(subsysid);
          if(info){
            store.dispatch("permission/setLoaded");
            store.dispatch("permission/setRouters",info.menu.children);
            router.addRoutes(info.optoins);
          }
        }
      }
      
      // if(subsysid){
      //   debugger
      //   //此处加载菜单
      //   let menusdata=syncRequest({
      //     url:'loadMenu',
      //     data:{root:subsysid}
      //   });
      //   if(menusdata.menu){
      //     let rootmenu=menusdata.menu;
      //     let children=rootmenu.children;
      //     router.addRoutes(children);
      //     next({ ...to, replace: true })
      //     return;
      //   }
      //   console.log(menu)
      // }
      //   next();
      //  return;
      // determine whether the user has obtained his permission roles through getInfo
      // next()

      // const hasRoles = store.getters.roles && store.getters.roles.length > 0
      // if (hasRoles) {
      //   next()
      // } else {
      //   try {
      //    // const { menuids ,roles} = await store.dispatch('user/getInfo')
      //     // generate accessible routes map based on roles
        // const accessRoutes = await store.dispatch('permission/generateRoutes',{roles:[], menuids:[]})
         next()
      //     // dynamically add accessible routes
      //    // router.addRoutes(accessRoutes)

      //     // hack method to ensure that addRoutes is complete
      //     // set the replace: true, so the navigation will not leave a history record
       //  next({ ...to, replace: true })
      //   } catch (error) {
      //     // remove token and go to login page to re-login
      //     await store.dispatch('user/resetToken')
      //     Message.error(error || 'Has Error')
      //     next(`/login?redirect=${to.path}`)
      //     NProgress.done()
      //   }
      // }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
